package it.koutifaris.travianmap.ui.animation;

import it.koutifaris.travianmap.physics.Motion;
import it.koutifaris.travianmap.physics.UniformAcceleratedMotion;
import it.koutifaris.travianmap.ui.viewstate.DynamicViewState;
import it.koutifaris.travianmap.ui.viewstate.ViewStateSource;
import android.util.Log;

public class FlingHelper implements Animation {

	private static final float DECELLERATION_PIX_MILLIS = -0.01f;

	private final Motion xMotion;
	private final Motion yMotion;
	private final ViewStateSource viewStateSource;
	private final float speedXSignum;
	private final float speedYSignum;

	public FlingHelper(ViewStateSource viewStateSource, float speedX, float speedY) {
		this.viewStateSource = viewStateSource;

		this.speedXSignum = Math.signum(speedX);
		this.speedYSignum = Math.signum(speedY);

		double angle = Math.atan2(speedY, speedX);
		float ax = (float) (DECELLERATION_PIX_MILLIS * Math.cos(angle));
		float ay = (float) (DECELLERATION_PIX_MILLIS * Math.sin(angle));

		this.xMotion = new UniformAcceleratedMotion(ax, speedX, getViewState().getX());
		this.yMotion = new UniformAcceleratedMotion(ay, speedY, getViewState().getY());
	}

	private DynamicViewState getViewState() {
		return viewStateSource.getViewState();
	}

	@Override
	public boolean isRunning() {
		Log.i("PIPPO", "isRunning() " + (Math.signum(xMotion.getState().speed()) == speedXSignum
				&& Math.signum(yMotion.getState().speed()) == speedYSignum));
		return Math.signum(xMotion.getState().speed()) == speedXSignum
				&& Math.signum(yMotion.getState().speed()) == speedYSignum;
	}

	@Override
	public void init() {
	}

	@Override
	public void paint(float alpha) {
		getViewState().updatePosition(
				(int) xMotion.getState().position(),
				(int) yMotion.getState().position());

	}

	@Override
	public void update(long totalTime, long deltaTime) {
		xMotion.update(deltaTime);
		yMotion.update(deltaTime);
	}

	@Override
	public void stopped(long totalTime, long deltaTime) {
	}

	@Override
	public int getUpdateRate() {
		return 25;
	}

}
